﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Results_Comparer
{
    public class HierarchicalViewBuilder
    {
        // Fields
        private bool nodefound;
        private TreeNode root = new TreeNode("", "");

        // Methods
        public void Build(string rdfId, string path, TreeNode node, int levels)
        {
            if (levels == this.GetLevels(path))
            {
                node.UpdateNodeRdfid(rdfId);
                node.UpdateNodeImportance(true);
            }
            else
            {
                TreeNode node2;
                this.nodefound = false;
                List<TreeNode> childs = node.childs;
                if (childs.Count == 0)
                {
                    node2 = new TreeNode(this.GetNameLevel(path, levels), rdfId);
                    childs.Add(node2);
                    this.Build(rdfId, path, node2, levels + 1);
                }
                else
                {
                    bool flag = false;
                    foreach (TreeNode node3 in childs)
                    {
                        if (node3.name.Equals(this.GetNameLevel(path, levels)))
                        {
                            this.Build(rdfId, path, node3, levels + 1);
                            flag = true;
                            this.nodefound = true;
                        }
                    }
                    if (!flag)
                    {
                        node2 = new TreeNode(this.GetNameLevel(path, levels), rdfId);
                        childs.Add(node2);
                        this.Build(rdfId, path, node2, levels + 1);
                    }
                }
            }
        }

        private int GetLevels(string path)
        {
            char[] separator = new char[] { '\\' };
            return path.Split(separator).Length;
        }

        private string GetNameLevel(string path, int level)
        {
            char[] separator = new char[] { '\\' };
            return path.Split(separator)[level];
        }

        public TreeNode Process(Dictionary<RdfId, List<RdfAttribute>> dict)
        {
            foreach (KeyValuePair<RdfId, List<RdfAttribute>> pair in dict)
            {
                this.Build(pair.Key.GetRdfId(), pair.Key.GetPath(), this.root, 0);
            }
            this.RemoveRdfIds(this.root);
            return this.root;
        }

        private void RemoveRdfIds(TreeNode root1)
        {
            if (root1.childs.Count != 0)
            {
                if (!root1.impnode)
                {
                    root1.myRdfId = null;
                }
                List<TreeNode> childs = root1.childs;
                foreach (TreeNode node in childs)
                {
                    this.RemoveRdfIds(node);
                }
            }
        }
    }
}